package com.lordjoe.collectiveintelligence;

import java.util.*;

/**
 * com.lordjoe.collectiveintelligence.MultiCluster
 *
 * @author Steve Lewis
 * @date Feb 25, 2009
 */
public class MultiCluster implements ICluster
{
    public static MultiCluster[] EMPTY_ARRAY = {};
    public static Class THIS_CLASS = MultiCluster.class;

    private final String m_Name;
    private double[] m_Values;
    private List<ICluster> m_Parts;

    public MultiCluster(String name,ICluster ... items)
    {
        m_Name = name;
        m_Parts = new ArrayList<ICluster>(Arrays.asList(items));

        resetValues();
    }
    
    public MultiCluster(String name,double[] items)
    {
        m_Name = name;
        m_Parts = new ArrayList<ICluster>();
        m_Values = items;
    }

    public void resetValues()
    {
        double[] vals = buildValues();
        if(vals.length > 0)
            setValues(vals);
        else
            m_Values = m_Values; // break here
    }

    protected void setValues(double[] vals)
    {
         m_Values = vals;
    }

    public String getName()
    {
        return m_Name;
    }

    @Override
    public String toString()
    {
        return getName();
    }

    public ICluster[] getParts()
    {
        return  m_Parts.toArray(ICluster.EMPTY_ARRAY);
    }

    public void addPart(ICluster part)
    {
        m_Parts.add(part);

    }

    public void clearParts()
    {
        m_Parts.clear();

    }

    protected double[]  buildValues()
    {
        ICluster[] clusters = getParts();
        if(clusters.length == 0)
            return new double[0];
        ICluster p1 = clusters[0];
        double[] val1 = p1.getValues();
        double[] ret = new double[val1.length];
        for (int i = 0; i < clusters.length; i++) {
            ICluster cluster = clusters[i];
            double[] vals = cluster.getValues();
            for (int j = 0; j < vals.length; j++) {
                ret[j] += vals[j];
            }
        }
        for (int i = 0; i < ret.length; i++) {
           ret[i] /= clusters.length;
        }
        return ret;
    }

    public double getDistance()
    {
         throw new UnsupportedOperationException("Fix This");
    }

    public int getWeight()
    {
        throw new UnsupportedOperationException("Fix This");
    }

    public double[] getValues()
    {
        return m_Values;
    }
}
